package com.powernode.util;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpStatus;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import com.powernode.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
 * 发送手机验证码的工具类
 */
@Component
@Slf4j
public class SmsUtil {

    @Value("${aliyun.sms.region}")
    private String region;
    @Value("${aliyun.sms.accessKey}")
    private String accessKey;
    @Value("${aliyun.sms.secret}")
    private String secret;
    @Value("${aliyun.sms.verification.signName}")
    private String signName;
    @Value("${aliyun.sms.verification.templateCode}")
    private String templateCode;

    public String sendVerification(String mobile){
        try {
            DefaultProfile profile = DefaultProfile.getProfile(region,accessKey,secret);
            IAcsClient client = new DefaultAcsClient(profile);
            SendSmsRequest request = new SendSmsRequest();

            request.setSignName(signName);
            request.setTemplateCode(templateCode);
            request.setPhoneNumbers(mobile);

            //随机生成一个四位数作为验证码
            String code = RandomUtil.randomNumbers(4);
            //设置验证码的模板
            request.setTemplateParam("{\"code\":" + code + "}");

            SendSmsResponse response = client.getAcsResponse(request);
            log.info(new Gson().toJson(response));

            return code;
        }catch (Exception e){
            e.printStackTrace();
            throw new BizException(HttpStatus.HTTP_INTERNAL_ERROR,e.getMessage());
        }
    }
}
